// packageA/pages/goodsAdd/goodsAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj: null,
    //传参来的id
    id: null,
    //是否是修改
    isEdit: false,
    //修改信息回显
    editInfo: {},
    //提交按钮禁用
    disabled: false,
    //避免表单重复提交
    code: null,
    //选择框
    showSelect: false,
    //选择数据
    selectList: [],
    //当前选择
    selectField: '',
    //选择框标题
    selectTitle: '',
    //显示选择搜索框
    showSelectSearch: false,
    //选择框搜索
    valueSearch: '',
    //原来信息
    oldInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取顶级部门信息
    this.getCompanyInfo();

    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('添加物资传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit: true
        })
        //获取修改数据
        this.getInfo();
      }
    }
  },

  //提交表单##
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo; 
    let user=app.globalData.userInfo;
    let oldInfo=td.oldInfo; 

    //表单验证
    let name=obj.name.trim();
    if(!this.formNotEmpty(name,'nameMessage','请输入物资名称')){
      return;
    }

    let code=obj.code.trim();
    if(!this.formNotEmpty(code,'codeMessage','请输入物资编码')){
      return;
    }

    let unit=obj.unit.trim();
    if(!this.formNotEmpty(unit,'unitMessage','请输入单位')){
      return;
    }

    if(!editInfo.classify){
      Toast.fail('请选择品类');
      return;
    }

    let price=obj.price.trim();
    if(!this.formNotEmpty(price,'priceMessage','请输入采购价')){
      return;
    }

    //采购价是数字
    if(!(/^\d+(\.\d+)?$/.test(price))){
      this.setData({
        priceMessage: '采购价为数字',
        disabled: true
      });
      return;
    }

    if(!editInfo.factory){
      Toast.fail('请选择厂家');
      return;
    }

    //权限
    let authArr=user.dataAuthorityOfUser.depart;
    authArr.push(user.depart, user.departObj[0].companyId);
    authArr=util.arrayRepeatEmpty(authArr);

    let param={
      className:'clientProducts',
      data:{
        requestToken: td.code,
        id: td.id,
        //名称
        name: name,
        //编码
        code: code,
        //单位
        unit: unit,
        //品类
        classify: editInfo.classify,
        //价格
        price: Number(price),
        //厂家
        factory: editInfo.factory,
        //所属
        subsidiaryOrgan: editInfo.subsidiaryOrgan,
        //平台
        appId: [app.globalData.myAppId],
        //数据权限
        dataAuthority:{
          depart: authArr
        },

        //非必填项
        //参数
        params: obj.params.trim(),
        //型号
        spec: obj.spec.trim(),
        //图
        pic: editInfo.pic
      }
    }  

    if(td.isEdit){
      //修改记录
      let editRecord=editInfo.editRecord || [];
      let eObj={},oldObj={};
     
      //物资名称
      if(name!=oldInfo.name){
        eObj.name=name;
        oldObj.name=oldInfo.name;
      }

      //物资编码
      if(code!=oldInfo.code){
        eObj.code=code;
        oldObj.code=oldInfo.code;
      }

      //单位
      if(unit!=oldInfo.unit){
        eObj.unit=unit;
        oldObj.unit=oldInfo.unit;
      }

      //品类
      if(editInfo.classify.id!=oldInfo.classify.id){
        eObj.classify=editInfo.classify.name;
        oldObj.classify=oldInfo.classify.name;
      }

      //型号
      let spec=obj.spec.trim();
      if(spec!=oldInfo.spec){
        eObj.spec=spec;
        oldObj.spec=oldInfo.spec;
      }

      //参数
      let params=obj.params.trim();
      if(params!=oldInfo.params){
        eObj.params=params;
        oldObj.params=oldInfo.params;
      }

      //价格
      if(price!=oldInfo.price){
        eObj.price=price;
        oldObj.price=oldInfo.price;
      }

      //厂家
      if(editInfo.factory.id!=oldInfo.factory.id){
        eObj.factory=editInfo.factory.name;
        oldObj.factory=oldInfo.factory.name;
      }

      //图片
      if(editInfo.pic && editInfo.pic.length){
        if(oldInfo.pic && oldInfo.pic.length){
          if(editInfo.pic[0].url != oldInfo.pic[0].url){
            eObj.pic=editInfo.pic[0].url;
            oldObj.pic=oldInfo.pic[0].url;
          }
        }else{
          eObj.pic=editInfo.pic[0].url;
          oldObj.pic=null;
        }
      }

      if(JSON.stringify(eObj)!='{}'){
        editRecord.push({
          editUser: user.userName,
          editBefore: oldObj,
          editAfter: eObj,
          editTime: util.timeFormat(new Date())
        });
      }

      if(editRecord.length){
        param.data.editRecord=editRecord;
      }  
    }else{
      //添加时传参创建人
      param.data.createUser={
        id: user.id,
        name: user.userName
      }
    }

    // console.log(param.data);
    // return;

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    }) 
  },

  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'clientProducts',
      data: {
        id: this.data.id,
        selectFields: ['id','name','pic','factory','spec','params','classify','unit','code','price','editRecord']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];

        //处理图片
        if(result.pic && result.pic.length){
          let arr=[];
          result.pic.forEach(item => {
            arr.push(item.url);
          });
          result.self_pic=arr;
        }

        console.log('物资回显');
        console.log(result);

        this.setData({
          editInfo: result,
          //深拷贝值不会被修改
          oldInfo: JSON.parse(JSON.stringify(result))
        })
      }
    }).catch((error) => {
    })
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },  

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;
    console.log(imgUrls);
    if(imgUrls.length){
      let imgArr=[];
      imgUrls.forEach(item => {
        imgArr.push({
          url: item
        });
      });
    
      let pic='editInfo.pic';
      let self_pic='editInfo.self_pic';
      this.setData({
        [pic]: imgArr,
        [self_pic]: imgUrls
      })
    }
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //品类
    if(field=='classify'){
      this.setData({
        selectTitle: '品类',
        showSelectSearch: true
      })
      this.getClassifyList();
    }

    //厂家
    if(field=='factory'){
      this.setData({
        selectTitle: '厂家',
        showSelectSearch: true
      })
      this.getFactoryList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //品类
    if(selectField=='classify'){
      obj='editInfo.classify';
    }

    //厂家
    if(selectField=='factory'){
      obj='editInfo.factory';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },  

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //品类
    if(selectField=='classify'){
      this.getClassifyList();
    }

    //厂家
    if(selectField=='factory'){
      this.getFactoryList();
    }
  },

  //查询品类
  getClassifyList(){
    let user=app.globalData.userInfo;
    let param = {
      isAuth: false,
      className: 'clientClassify',
      data: {
        searchAll: true,
        selectFields: ['id','name','subsidiaryOrgan'],
        'subsidiaryOrgan.id': user.departObj[0].companyId
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj:{
              id: item.id,
              name: item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询厂家
  getFactoryList(){
    let user=app.globalData.userInfo;
    let param = {
      isAuth: false,
      className: 'clientSupplierFactories',
      data: {
        searchAll: true,
        selectFields: ['id','name','subsidiaryOrgan'],
        'subsidiaryOrgan.id': user.departObj[0].companyId
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj:{
              id: item.id,
              name: item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //获取顶级部门信息
  getCompanyInfo(){
    let user=app.globalData.userInfo;

    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        id: user.depart,
        selectFields: ['id','name','company']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];

        if(result.company && result.company.length){
          let company=result.company[0];

          let info='editInfo.subsidiaryOrgan';

          this.setData({
            [info]: {
              id: company.id,
              name: company.name
            }
          })  
        }
      }
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})